/*
    Copyright (C) 2010-2011 AmigaVR
    
    This file is part of AmigaVR.
    Written by Laügt Franz <znarf94@gmail.com>

    AmigaVR is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AmigaVR is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AmigaVR.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "global.h"

void minit ( void )
{
	PORTF.DIR = _BV(FLASH_CE) | _BV(FLASH_OE) | _BV(FLASH_WE); // activation des ports PF0, PF1, PF2 en Sortie (1).
	PORTF.OUT |= _BV(FLASH_CE) | _BV(FLASH_OE) | _BV(FLASH_WE); // mise à 1 des ports PF0, PF1, PF2.

	PORTJ.DIR = 0xFF; // ports J et K en Sortie (1).
	PORTK.DIR = 0xFF;
	PORTH.DIR = 0x00; // port H en Entrée (0), par défaut.
}

uint8_t mread_byte ( uint16_t addr )
{
	uint8_t data;

	PORTJ.OUT = (uint8_t) addr;
	PORTK.OUT = (uint8_t) (addr >> 8);

	PORTH.DIR = 0x00; // port H en Entrée (0).

	PORTF.OUT &= ~(_BV(FLASH_CE) | _BV(FLASH_OE)); // mise à 0 de FLASH_CE et FLASH_OE.

	data = PORTH.IN; // lecture du mot.

	PORTF.OUT |= (_BV(FLASH_CE) | _BV(FLASH_OE)); // re-mise à 1 de FLASH_CE et FLASH_OE.

	return data;
}

uint16_t mread_word ( uint16_t addr )
{
	uint8_t datah,datal;
	uint16_t data;
	
	datal = mread_byte(addr);
	datah = mread_byte(addr+1);
	
	data = (datah<<8) + datal;
	
	return data;
}

uint32_t mread_dword ( uint16_t addr )
{
	return (uint32_t)(mread_byte (addr) + ((uint32_t)mread_byte(addr+1)<<8) + ((uint32_t)mread_byte(addr+2)<<16) + ((uint32_t)mread_byte(addr+3)<<24));
}

uint8_t mwrite_byte ( uint16_t addr , uint8_t data )
{
	uint8_t data_test;
	
	PORTH.DIR = 0xFF; // port H en Sortie (1).
	
	PORTJ.OUT = (uint8_t) addr;
	PORTK.OUT = (uint8_t) (addr >> 8);

	PORTH.OUT = data;

	PORTF.OUT &= ~(_BV(FLASH_CE) | _BV(FLASH_WE));
	PORTF.OUT |= (_BV(FLASH_CE) | _BV(FLASH_WE));

	data_test = mread_byte(addr);

	if(data_test == data)
		return 0;
	else
		return 1;
}

